#!/bin/bash

# 配置数据库连接参数
DB_USER="root"
DB_PASSWORD="cfCNxfeea536AttJ"
DB_HOST="182.92.71.132"
DB_PORT="13306"
OLD_DB_NAME="zct_prod"
NEW_DB_NAME="zct-prod"
IMPORT_FILE="zct-prod.sql"

# 检查依赖和文件
if ! command -v mysql &> /dev/null; then
    echo "错误: mysql 客户端未安装"
    exit 1
fi

if [ ! -f "$IMPORT_FILE" ]; then
    echo "❌ 错误: 导入文件 $IMPORT_FILE 不存在"
    exit 1
fi

# 使用环境变量传递密码
export MYSQL_PWD="${DB_PASSWORD}"

# 创建临时数据库
echo "正在创建临时数据库 ${OLD_DB_NAME}..."
mysql -h ${DB_HOST} -P ${DB_PORT} -u ${DB_USER} -e "CREATE DATABASE IF NOT EXISTS \`${OLD_DB_NAME}\`;"

if [ $? -ne 0 ]; then
    echo "❌ 临时数据库 ${OLD_DB_NAME} 创建失败"
    exit 1
fi

# 创建目标数据库并清空现有表
echo "正在准备目标数据库 ${NEW_DB_NAME}..."
mysql -h ${DB_HOST} -P ${DB_PORT} -u ${DB_USER} -e "CREATE DATABASE IF NOT EXISTS \`${NEW_DB_NAME}\`;"

# 获取并删除目标数据库中所有表
TABLES=$(mysql -h ${DB_HOST} -P ${DB_PORT} -u ${DB_USER} ${NEW_DB_NAME} -e "SHOW TABLES;" | tail -n +2)
for TABLE in $TABLES; do
    echo "删除表: ${TABLE}"
    mysql -h ${DB_HOST} -P ${DB_PORT} -u ${DB_USER} ${NEW_DB_NAME} -e "DROP TABLE \`${TABLE}\`;"
done

# 导入数据到临时库
echo "正在导入数据到临时库 ${OLD_DB_NAME}..."
mysql -h ${DB_HOST} -P ${DB_PORT} -u ${DB_USER} ${OLD_DB_NAME} < ${IMPORT_FILE} 2> import_errors.log

if [ $? -eq 0 ]; then
    echo "✅ 数据导入成功"

    # 转移数据到目标库
    tables=$(mysql -h ${DB_HOST} -P ${DB_PORT} -u ${DB_USER} ${OLD_DB_NAME} -e "SHOW TABLES;" | tail -n +2)
    for table in $tables; do
        mysql -h ${DB_HOST} -P ${DB_PORT} -u ${DB_USER} -e "RENAME TABLE \`${OLD_DB_NAME}\`.\`${table}\` TO \`${NEW_DB_NAME}\`.\`${table}\`;"
    done

    # 清理临时库
    mysql -h ${DB_HOST} -P ${DB_PORT} -u ${DB_USER} -e "DROP DATABASE \`${OLD_DB_NAME}\`;"
    echo "✅ 数据转移完成"
else
    echo "❌ 数据导入失败"
    cat import_errors.log
    exit 1
fi